/**
 * @file app\tasks\mobus\_passthrough.c
 *
 * Copyright (C) 2023
 *
 * _passthrough.c is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * @author HinsShum hinsshum@qq.com
 *
 * @encoding utf-8
 */

/*---------- includes ----------*/
#include "protocol_mobus.h"
#include "resources.h"
#include "storage.h"

/*---------- macro ----------*/
/*---------- type define ----------*/
/*---------- variable prototype ----------*/
/*---------- function prototype ----------*/
static void report_which_channel_sta(mobus_device_t self, uint8_t channel);
/*---------- variable ----------*/
static struct storage_led_struct* ledT = NULL;
static struct storage_key_struct* keyT = NULL;

static struct protocol_callback cmd_struct_callback[] = {
    {MOBUS_CMD_QUERY_STATUS, report_which_channel_sta},
    // {MOBUS_CMD_QUERY_ONLINE,}
    // {MOBUS_CMD_QUERY_INFO,    } /* data */
};
void report_which_channel_sta(mobus_device_t self, uint8_t channel) {
    uint8_t data_buffer[4] = { 0 };
    if (channel >= 1) {
        data_buffer[0] = no_storage.temp_relay.relay_out[channel - 1];
        protocol_mobus_dev_report(MOBUS_FRAME_TYPE_UPLOAD_STATUS, channel, data_buffer, 1);
    }
    else {
        ledT = (struct storage_led_struct*)storage_get(STORAGE_AREA_LIGHT_MODE);
        keyT = (struct storage_key_struct*)storage_get(STORAGE_AREA_KEY);
        assert(ledT);
        assert(keyT);
        if (ledT->assign_bright == 0)
            data_buffer[0] = 0;
        else {
            data_buffer[0] = 1;
        }
        data_buffer[1] = ledT->assign_bright / 2.5;
        data_buffer[2] = keyT->dis_en_flag & 0xff;
        if (no_storage.temp_key.key_num <= 8)
            data_buffer[3] = 0;
        else
            data_buffer[3] = (keyT->dis_en_flag >> 8) & 0xff;
        protocol_mobus_dev_report(MOBUS_FRAME_TYPE_UPLOAD_STATUS, channel, data_buffer, 4);
    }
}
/*---------- function ----------*/
static void _passthrough(mobus_device_t self, uint8_t sub_channel,
    mobus_frame_type_t type, const uint8_t* pdata,
    uint16_t length) {
    void (*cb)(mobus_device_t self, uint8_t channel) = NULL;

    cb = protocol_callback_find(pdata[0], cmd_struct_callback, ARRAY_SIZE(cmd_struct_callback));
    assert(cb);
    if (cb) {
        cb(self, sub_channel);
    }
}
